namespace Yaaf.Wp7.AdvancedExplorer
{
    using System;
    using System.Collections.Generic;

    public static class Extensions
    {
        /// <summary>
        /// Sorts the given collections, assumes that only one! item (which is on the last position) is wrong!
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="values"></param>
        /// <param name="comparison"></param>
        public static void SortOne<T>(IList<T> values, Comparison<T> comparison)
        {
            var last = values.Count - 1;
            T tohandle = values[last];
            values.Remove(tohandle);

            int toInsert = FindSortedIndex(values, tohandle, comparison);
            values.Insert(toInsert, tohandle);
        }

        public static int FindSortedIndex<T>(this IList<T> values, T item, Comparison<T> comparison)
        {
            int currentButtomLimit = 0;
            int currentTopLimit = values.Count;

            while (currentTopLimit != currentButtomLimit)
            {
                var index = (currentTopLimit + currentButtomLimit) / 2;
                var compare = comparison(item, values[index]);
                if (compare > 0) // item > values[index]
                {
                    if (currentTopLimit == currentButtomLimit + 1)
                    {
                        return currentTopLimit;
                    }

                    currentButtomLimit = index;
                }
                else if (compare < 0) // item < values[index]
                {
                    currentTopLimit = index;
                }
                else
                {
                    return index;
                }
            }

            return currentTopLimit;
        }
    }
}